package com.youzhi.backend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youzhi.backend.dto.OperateLogTypeEnum;
import com.youzhi.backend.dto.Page;
import com.youzhi.backend.entity.Privilege;
import com.youzhi.backend.entity.Role;
import com.youzhi.backend.entity.RolePrivilege;
import com.youzhi.backend.exception.EcpEnum;
import com.youzhi.backend.exception.YouZhiException;
import com.youzhi.backend.mapper.RoleMapper;
import com.youzhi.backend.request.AddPrivilegeRequest;
import com.youzhi.backend.request.AddRoleRequest;
import com.youzhi.backend.request.RolePageRequest;
import com.youzhi.backend.request.UpdateRoleRequest;
import com.youzhi.backend.service.*;
import com.youzhi.backend.util.CommonUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author xumeng
 * @since 2022-11-18
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {


    @Autowired
    private IUserRoleService userRoleService;


    @Autowired
    private IRolePrivilegeService rolePrivilegeService;


    @Autowired
    private IPrivilegeService privilegeService;

    @Autowired
    private IOperateLogService operateLogService;


    @Autowired
    private IUserSessionService userSessionService;


    /**
     * 管理员角色id
     */
    public static int admin_role_id = 1;


    @Override
    public void addRole(AddRoleRequest request) {

        Long count = countByName(request.getName());
        if (count > 0l) {
            throw YouZhiException.newException(EcpEnum.role_name_repeat);
        }

        Role role = new Role();
        BeanUtils.copyProperties(request, role);
        role.setCode(CommonUtil.getPinyin(role.getName()));
        String currentUser = userSessionService.getCurrentUser();
        role.setCreateBy(currentUser);
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        save(role);

        //添加操作日志
        operateLogService.addOperateLog(OperateLogTypeEnum.add, "添加角色 " + request.getName(), role.getId().toString());

    }


    @Override
    public IPage<Role> pageRequest(RolePageRequest request) {

        QueryWrapper queryWrapper = new QueryWrapper();
        if (StrUtil.isNotEmpty(request.getName())) {
            queryWrapper.like(Role.Fields.name, request.getName());
        }

        queryWrapper.orderByDesc(Role.Fields.createTime);

        return page(Page.ofPage(request), queryWrapper);
    }


    private Long countByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(Role.Fields.name, name);
        return count(queryWrapper);
    }

    @Override
    public void updateRole(UpdateRoleRequest request) {
        Role role = new Role();
        BeanUtils.copyProperties(request, role);
        role.setUpdateTime(new Date());
        updateById(role);
        //添加操作日志
        operateLogService.addOperateLog(OperateLogTypeEnum.edit, "更新角色信息", role.getId().toString());
    }


    public void deleteRoles(Collection ids) {

        List collect = (List) ids.stream()
                .filter(e -> Integer.parseInt(e.toString()) != admin_role_id)
                .collect(Collectors.toList());


        //批量删除角色
        removeBatchByIds(collect);

        //批量删除用户角色关联
        userRoleService.deleteByRoleIds(collect);

        //批量删除角色权限关联
        rolePrivilegeService.deleteByRoleIds(collect);

        //添加操作日志
        operateLogService.addOperateLog(OperateLogTypeEnum.delete, "删除角色", CollUtil.join(collect, ","));

    }


    @Override
    public void addPrivilege(AddPrivilegeRequest request) {

        //删除老的权限
        rolePrivilegeService.deleteByRoleIds(CollUtil.newArrayList(request.getRoleId()));

        //添加新的权限
        if (CollUtil.isNotEmpty(request.getCodes())) {

            List<Privilege> privileges = privilegeService.getByCodes(request.getCodes());

            Role role = getById(request.getRoleId());

            List<RolePrivilege> list = convertRolePrivilege(role, privileges);

            rolePrivilegeService.saveBatch(list);

        }

        //添加操作日志
        operateLogService.addOperateLog(OperateLogTypeEnum.edit, "修改角色权限", request.getRoleId().toString());
    }


    private List<RolePrivilege> convertRolePrivilege(Role role, List<Privilege> privileges) {
        return privileges.stream().map(privilege -> {
            RolePrivilege rolePrivilege = new RolePrivilege();
            rolePrivilege.setRoleId(role.getId());
            rolePrivilege.setRoleCode(role.getCode());
            rolePrivilege.setPrivilegeCode(privilege.getCode());
            rolePrivilege.setPrivilegeId(privilege.getId());
            rolePrivilege.setCreateTime(new Date());
            rolePrivilege.setUpdateTime(new Date());
            return rolePrivilege;
        }).collect(Collectors.toList());

    }


}
